<template>
    <div class="sms-login">
        <el-form :model="ruleForm" :rules="rules" ref="ruleFormRef">
            <el-form-item label="" prop="phone">
              <el-input
                :maxlength="11"
                placeholder="请输入手机号"
                prefix-icon="Cellphone"
                v-model="ruleForm.phone"
              />
            </el-form-item>
            <el-form-item class="vericode" label="" prop="verificationCode">
              <el-input
                :maxlength="4"
                placeholder="请输入验证码"
                prefix-icon="Message"
                v-model="ruleForm.verificationCode"
              />
              <el-button :disabled="!!smsCount" type="primary" class="code-box" @click="onImgCaptcha">
                {{ smsCount ? `${smsCount}s` : '获取短信验证码' }}
              </el-button>
            </el-form-item>
            <el-form-item>
            <el-button type="primary" :disabled="loading" class="login-btn" @click="onSubmit">
              {{ loading ? '登录中...' : '登录'}}
            </el-button>
            </el-form-item>
        </el-form>
        <Verify
            @success="verifySuccess"
            :isShow="isVerifyCodeShow"
            :imgSize="{ width: '330px', height: '155px' }"
            :getUrl="'/uc/api/captcha/get'"
            :checkUrl="'/uc/api/captcha/check'"
            :gateway="gateway"
            ref="verify"
        />
    </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref, onMounted, onUnmounted } from 'vue'
import * as Verify from 'if-verify'
import 'if-verify/dist/if-verify.css'
import { LoginRequest } from '@/services/login'
import useCommonLogin from '../hooks/useLogin'
import { phoneValidator } from '@/utils/validator/tool'
import {
  ACCOUNT_TYPE_MAP,
  CERTIFICATION_TYPE_MAP,
  LOGIN_TYPE_MAP,
  LOGIN_METHOD_MAP,
  SMS_TYPE
} from '@/global-config/const'
import {
  countDownInterval,
  browserTabChangeHandler,
  browserTabChangeListener
} from '@/utils/count-down'
import { loginSmsCache } from '../config'

export default defineComponent({
  name: 'smsLoginPage',
  components: {
    Verify
  },
  setup() {
    const ruleForm = reactive<Record<string, any>>({
      phone: '',
      verificationCode: ''
    })
    const currentLoginWay = 'sms'
    // 解构出通用状态和处理程序
    const {
      ruleFormRef,
      loading,
      smsCount,
      smsTimer,
      onSubmit
    } = useCommonLogin(ruleForm, currentLoginWay)
    const rules = reactive<any>({
      phone: [{ required: true, trigger: 'blur', validator: phoneValidator() }],
      verificationCode: [{ required: true, message: '请输入验证码！', trigger: 'blur' }],
    })
    const isVerifyCodeShow = ref<boolean>(false)
    const gateway = import.meta.env.VITE_APP_URL_GATEWAY
    // ------------------------ 方法 ------------------------
    // 获取短信验证码
    const onImgCaptcha = async () => {
      // 1. 校验手机号
      if (!ruleForm.phone) {
        ruleFormRef.value.validateField('phone') // 清理当前字段校验
        return
      }
      // 2. 滑块验证码
      isVerifyCodeShow.value = !isVerifyCodeShow.value
    }
    // 验证码成功的回调
    const verifySuccess = async (token: any) => {
      const { phone } = ruleForm
      const params = {
        phone,
        accountType: ACCOUNT_TYPE_MAP.phoneCode,
        cerificationType: CERTIFICATION_TYPE_MAP.login,
        captchaVerification: token?.captchaVerification,
        loginType: LOGIN_TYPE_MAP.code,
        loginMethod: LOGIN_METHOD_MAP.phone,
        smsType: SMS_TYPE.if
      }
      const res = await LoginRequest.getSmsCertificate(params)
      if (res.code !== 200) {
        return
      }
      ruleForm.verificationCode = res?.data?.smsCode || '' // 验证码同步到页面上
      ruleForm.verificationCode && ruleFormRef.value.clearValidate('verificationCode') // 清理当前字段校验
      countDownInterval({ smsCount, smsTimer }, true, loginSmsCache) // 倒计时处理
    }
    // tab变化监听处理器
    const browserTabChange = () => {
      browserTabChangeHandler({ smsCount, smsTimer }, loginSmsCache)
    }
    onMounted(() => {
      const params = { smsCount, smsTimer }
      countDownInterval(params, false, loginSmsCache) // 倒计时处理
      browserTabChangeListener(true, { ...params, browserTabChange }) // 监听tab
    })
    onUnmounted(() => {
      browserTabChangeListener(false, { smsTimer, browserTabChange }) // 移除监听tab
    })
    return {
      ruleForm,
      rules,
      ruleFormRef,
      smsCount,
      loading,
      isVerifyCodeShow,
      gateway,
      // methods
      onImgCaptcha,
      verifySuccess,
      onSubmit
    }
  },
})
</script>

<style scoped lang="less">
@import "../style/common.less";
.sms-login {
  .login-btn {
    width: 280px;
    height: 40px;
    border-radius: 100px;
  }
  .login-content {
    display: flex;
    margin-left: 200px;
    justify-content: center;
    align-items: center;
  }
  :deep(.el-form-item__content) {
    display: block;
  }
  :deep(.code-box) {
    width: 140px;
    height: 32px;
    margin-left: 10px;
    display: inline-block;
    vertical-align: top;
    margin-top: 10px;
  }
}
</style>
